package com.dongdongshop.controller;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.dongdongshop.domain.AjaxResult;
import em.ResuleEnum;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


@Controller
@RequestMapping("file")
public class FileController {

    @RequestMapping("upLoadFile")
    @ResponseBody
    public AjaxResult upLoadFile(@RequestParam("image") MultipartFile image){
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String http ="https://";
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5t9e5uqUzuT2j8s3wf4n";
        String accessKeySecret = "VF9maLVsBsXOkjmOcgoIyFAOgOBPRt";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "dongdongshop21091";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = "image/"+image.getOriginalFilename();
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(http+endpoint, accessKeyId, accessKeySecret);
        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName,image.getInputStream());
            // 上传字符串。
            ossClient.putObject(putObjectRequest);
        } catch (Exception oe) {
            oe.printStackTrace();
        }  finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        StringBuffer sb = new StringBuffer();
        sb.append(http).append(bucketName).append(".").append(endpoint).append("/").append(objectName);
        System.out.println(sb.toString());
        return AjaxResult.R(ResuleEnum.SUCCESS).setData(sb.toString());
    }

    @RequestMapping("download")
    @ResponseBody
    public String download(String filename){
        return filename;
    }
}
